package leetcode.median;

/**
 * ClassName: $79_SearchWord
 * Description:
 * date: 2022-02-19 17:38
 *
 * @author liyifan
 */
public class $79_SearchWord {
    int row;
    int col;
    boolean[][] vis;
    public boolean exist(char[][] board, String word) {
        row = board.length;
        col = board[0].length;
        vis = new boolean[row][col];
        for (int i = 0;i < row;i++){
            for (int j =0 ;j < col;j++) {
                if (board[i][j] == word.charAt(0)) {
                    if (dfs(board, word, i, j, 0)){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, String word, int i, int j, int index) {
        if (!isArea(board, i, j) || vis[i][j])
            return false;
        if (board[i][j] != word.charAt(index)) {
            return false;
        }
        if (index == word.length() - 1) {
            return true;
        }


        vis[i][j] = true;
        boolean res = dfs(board, word, i + 1, j, index + 1)||
                        dfs(board, word, i - 1, j, index + 1)||
                        dfs(board, word, i, j + 1, index + 1)||
                        dfs(board, word, i, j - 1, index + 1);

        vis[i][j] = false;
        return res;
    }

    private boolean isArea(char[][] board, int i, int j){
        return i >= 0 && i < row && j >= 0 && j < col;
    }
}
